package disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import disruptor.event.ValueEvent;
import disruptor.event.handler.ValueEventHandler;
import disruptor.factory.ValueEventFactory;

import java.util.concurrent.Executors;

/**
 * @ClassName SingleProducerSingleConsumer
 * @PackageName disruptor
 * @projectName myThread
 * @Description TODO
 * @Author games
 * @Date 2025/9/8 下午5:25
 * @Version 1.0
 */
public class SingleProducerSingleConsumer {
    public static void run() throws InterruptedException {
        // 创建 Disruptor - 单生产者模式
        Disruptor<ValueEvent> disruptor = new Disruptor<>(
                new ValueEventFactory(),
                1024,
                Executors.defaultThreadFactory(),
                com.lmax.disruptor.dsl.ProducerType.MULTI,
                new com.lmax.disruptor.SleepingWaitStrategy()
        );

        // 连接单个事件处理器
        disruptor.handleEventsWith(new ValueEventHandler());

        // 启动 Disruptor
        disruptor.start();

        // 获取 Ring Buffer
        RingBuffer<ValueEvent> ringBuffer = disruptor.getRingBuffer();

        // 生产事件
        for (int i = 0; i < 5; i++) {
            long sequence = ringBuffer.next();
            try {
                ValueEvent event = ringBuffer.get(sequence);
                event.setValue(i);
            } finally {
                ringBuffer.publish(sequence);
            }
            Thread.sleep(1000); // 模拟生产间隔
        }

        Thread.sleep(2000); // 等待所有事件处理完成
        disruptor.shutdown();
    }
}

